package com.common.init;

import com.common.util.SnowflakeIdUtil;
import com.common.util.SpringContextUtil;
import com.modules.log.entity.LogOnlineCountEntity;
import com.modules.log.service.LogOnlineCountService;
import com.modules.timer.dao.TimerTaskDao;
import com.modules.timer.entity.TimerTaskEntity;
import com.modules.timer.util.TimerUtil;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.SessionDAO;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.quartz.CronTrigger;
import org.quartz.Scheduler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import javax.annotation.PostConstruct;
import java.util.Collection;
import java.util.Date;
import java.util.List;

@Configuration
@EnableScheduling
public class TimerInit {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private Scheduler scheduler;

    @Autowired
    private TimerTaskDao timerTaskDao;

    @Autowired
    private LogOnlineCountService logOnlineCountService;

    @PostConstruct
    private void timerInit(){
        logger.info("定时任务启动初始化。。。。。。。");
        List<TimerTaskEntity> list =  timerTaskDao.selectAll();
        if(list != null && list.size()>0){
            for(TimerTaskEntity timerTask:list){
                CronTrigger cronTrigger = TimerUtil.getCronTrigger(scheduler, timerTask.getTaskId());
                //如果不存在，则创建
                if(cronTrigger == null) {
                    TimerUtil.createScheduleJob(scheduler, timerTask);
                }else {
                    TimerUtil.updateScheduleJob(scheduler, timerTask);
                }
            }
        }
        logger.info("定时任务初始化完成。。。。。。。");
    }

    //-----------------------------------------------------------------------------------------------------
    //系统化定时任务，单独设置，不在timer模块监控范围之内

    //每小时记录一次在线人数
    @Scheduled(cron = "0 0 */1 * * ?")
    private void onlineCountListener(){
        SessionDAO sessionDAO = ((DefaultWebSessionManager)SpringContextUtil.getBean("sessionManager")).getSessionDAO();
        Collection<Session> sessions = sessionDAO.getActiveSessions();
        logger.info("当前在线人数："+sessions.size());
        LogOnlineCountEntity onlineCount = new LogOnlineCountEntity();
        onlineCount.setCreateTime(new Date());
        onlineCount.setOnlineCount(sessions.size());
        SnowflakeIdUtil idWorker = new SnowflakeIdUtil(0, 0);
        onlineCount.setOnlineCountId(idWorker.nextId());
        logOnlineCountService.insert(onlineCount);

      }

}
